<template>
  <div ref="chartDom" class="app-chart" style="width: 100%; height: 100%;"></div>
</template>

<script setup>
  import * as echarts from 'echarts';
  import { onMounted, ref, defineProps, onUnmounted, watch } from "vue";
  import useHookData from '@/hook/data';

  let reInstantiate = false // 是否重新实例化图表

  const props = defineProps({
    chartId: {
      type: String,
      default: ''
    },

    // 接口参数
    params: {
      type: Object,
      default: () => ({})
    },

    // 父组件传入的数据，如不为 null，将不会去请求接口数据
    data: {
      type: [Array, Object, String, Number],
      default: () => null
    },

    // 图表类型（bar、line...）
    type: {
      type: String,
      default: ''
    },

    // 图表方向（v: 竖向、h ：横向）
    direction: {
      type: String,
      default: ''
    }
  });


  const {getData} = useHookData(props);
  let myChart = null;
  const chartDom = ref(null);

  // 是否应该在这里监听高度变换？
  const theResizeObserver = new ResizeObserver(resize);

  onMounted(()=> {
    myChart = echarts.init(chartDom.value); /*, 'dark'*/
    theResizeObserver.observe(chartDom.value);
    initData();
  });

  onUnmounted(()=> {
    chartDom.value && theResizeObserver.unobserve(chartDom.value);
    myChart && myChart.dispose()
  })

  // TODO
  watch(
    [
      () => props.data,
      () => props.type,
      () => props.direction
    ],
    (val) => {
      // 如果 type，direction 变化，将会重新实例化echarts，避免重复绑定chart事件
      if(val[1] || val[2]) reInstantiate = true

      initData()
    },
    { immediate: false }
  )

  // 动态导入chart文件
  async function getImportChart() {
    try {
      const pathArr = props.chartId.split('-')
      const fileName = `app-${pathArr[0]}-${pathArr[1]}${props.type ? '-'+props.type : ''}${props.direction ? '-'+props.direction : ''}`
      console.log(`fileName=>`, fileName);
      return await import(`../../chart/app-${pathArr[0]}/app-${pathArr[0]}-${pathArr[1]}/${fileName}.js`);
    } catch (e) {
      console.info('获取图表js文件错误')
      return null
    }
  }

  function resize(){
    myChart && myChart.resize();
  }

  function initData() {
    getData().then(res=> {
      myChart && initChart(res)
    }).catch(err=>{
      console.log(err)
    })
  }

  async function initChart(data) {

    if(reInstantiate) {
      myChart && myChart.dispose()
      myChart = echarts.init(chartDom.value);
      reInstantiate = false
    }

    const {getChartOption, handleChartEvent} = await getImportChart();
    const option = getChartOption && getChartOption(data, myChart);
    option && myChart.setOption(option, true);
    handleChartEvent && handleChartEvent(data, myChart);
  }

</script>

<style lang="scss" scoped>
  .app-chart {
    min-height: px(200);
  }
</style>